package com.csaba.connector.otp;

import java.util.StringTokenizer;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.csaba.connector.I18NServiceException;
import com.csaba.connector.ServiceException;
import com.csaba.connector.model.Session;
import com.csaba.connector.otp.model.OTPBank;
import com.csaba.connector.otp.model.OTPRequestFactory;
import com.csaba.connector.otp.model.OTPSession;
import com.csaba.connector.otp.parser.OTPCodes;
import com.csaba.connector.service.AbstractBankService;

public class OTPGetTokenService extends AbstractBankService
{

	@Override
	public void execute( final Session session ) throws ServiceException
	{
		if ( !( session instanceof OTPSession ) )
			throw new ServiceException("Incompatible session " + OTPBank.class + " != " + session.getClass().getName());

		final OTPSession otp = (OTPSession) session;

		final NameValuePair[] params = new NameValuePair[] { new BasicNameValuePair("cb", "AV.tokenCallback"), //
				new BasicNameValuePair(OTPCodes.RP_DIA, (String) otp.getRemoteProperty(OTPCodes.RP_DIA)), //
				new BasicNameValuePair(OTPCodes.RP_GWBID, (String) otp.getRemoteProperty(OTPCodes.RP_GWBID)), //
				new BasicNameValuePair("contractDate", (String) otp.getRemoteProperty(OTPCodes.RP_STARTING_DATE)), //
		};

		final String tokenResult = otp.doPost(OTPRequestFactory.HOMEBANK_SERVER_URL
				+ OTPRequestFactory.ROOT_REQUEST_GETTOKEN, params);

		otp.debugFile("gettoken.js", tokenResult);

		final StringTokenizer st = new StringTokenizer(tokenResult, "'");
		if ( st.countTokens() > 2 )
		{
			st.nextToken();
			final String token = st.nextToken();
			otp.setRemoteProperty(OTPCodes.RP_LASTTOKEN, token);
		}
		else
		{
			throw new I18NServiceException(OTPBank.getInstance(), "msg.loginError1",
					"Invalid or missing get token reply.");
		}
	}

}
